/**
 * module_config.js
 * PLM项目模块统一配置入口
 * 使用统一配置入口模式，集中管理模块引用
 */

// 使用静态路径导入核心模块
let TimeHelper, CloudHelper, DataHelper, PageHelper, CacheHelper;
let ValidateHelper, RouterHelper, FileHelper;
let researchStateBiz;

// 1. 从固定路径导入核心助手模块
try {
  TimeHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载time_helper，路径: ../../../helpers/time_helper.js');
} catch (e) {
  // 提供备用实现
  console.warn('加载time_helper失败，使用备用实现');
  TimeHelper = {
    formatDate: (date, format = 'YYYY-MM-DD') => {
      const d = date ? new Date(date) : new Date();
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const hours = d.getHours().toString().padStart(2, '0');
      const minutes = d.getMinutes().toString().padStart(2, '0');
      const seconds = d.getSeconds().toString().padStart(2, '0');
      
      return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
    },
    timestamp2Time: (timestamp, fmt = 'YYYY-MM-DD HH:mm:ss') => {
      if (!timestamp) return '';
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      
      return fmt
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
    },
    timestamp2Date: function(timestamp, fmt = 'YYYY-MM-DD') {
      return this.timestamp2Time(timestamp, fmt);
    },
    getNow: function(format = 'YYYY-MM-DD') {
      return this.formatDate(new Date(), format);
    }
  };
}

// 2. 加载CloudHelper
try {
  CloudHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载cloud_helper，路径: ../../../helpers/cloud_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载cloud_helper失败，使用备用实现');
  CloudHelper = {
    callCloudData: async function(route, params = {}, options = {}) {
      console.log('[模拟]CloudHelper.callCloudData', route, params);
      // 模拟异步加载延迟
      return new Promise((resolve) => {
        setTimeout(() => {
          if (route === 'plm/project_list') {
            resolve({
              list: [
                { 
                  id: 'mock001', 
                  name: '模拟项目1', 
                  status: 1,
                  CREATETIME: Math.floor(Date.now() / 1000) - 86400, 
                  UPDATETIME: Math.floor(Date.now() / 1000)
                },
                { 
                  id: 'mock002', 
                  name: '模拟项目2', 
                  status: 2,
                  CREATETIME: Math.floor(Date.now() / 1000) - 172800, 
                  UPDATETIME: Math.floor(Date.now() / 1000)
                }
              ],
              total: 2
            });
          } else {
            resolve({ list: [], total: 0 });
          }
        }, 500);
      });
    },
    callCloud: async function(route, params = {}, options = {}) {
      console.log('[模拟]CloudHelper.callCloud', route, params);
      return { code: 0, data: {}, message: 'mock success' };
    }
  };
}

// 3. 加载DataHelper
try {
  DataHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载data_helper，路径: ../../../helpers/data_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载data_helper失败，使用备用实现');
  DataHelper = {
    deepClone: (obj) => {
      if (obj === null || typeof obj !== 'object') {
        return obj;
      }
      
      const result = Array.isArray(obj) ? [] : {};
      
      for (let key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          result[key] = DataHelper.deepClone(obj[key]);
        }
      }
      
      return result;
    },
    isEmpty: (value) => {
      if (value === undefined || value === null) return true;
      if (typeof value === 'string') return value.trim() === '';
      if (Array.isArray(value)) return value.length === 0;
      if (typeof value === 'object') return Object.keys(value).length === 0;
      return false;
    }
  };
}

// 4. 加载PageHelper
try {
  PageHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载page_helper，路径: ../../../helpers/page_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载page_helper失败，使用备用实现');
  PageHelper = {
    showSuccToast: (title = '操作成功', duration = 1500) => {
      wx.showToast({
        title: title,
        icon: 'success',
        duration: duration
      });
      return new Promise(resolve => setTimeout(resolve, duration));
    },
    showErrToast: (title = '操作失败', duration = 1500) => {
      wx.showToast({
        title: title,
        icon: 'none',
        duration: duration
      });
      return new Promise(resolve => setTimeout(resolve, duration));
    }
  };
}

// 5. 加载ValidateHelper
try {
  ValidateHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载validate_helper，路径: ../../../helpers/validate_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载validate_helper失败，使用备用实现');
  ValidateHelper = {
    checkRequired: (val, desc = '') => val ? '' : `${desc}不能为空`,
    isNotEmpty: (val) => !!val && val !== ''
  };
}

// 6. 加载RouterHelper
try {
  RouterHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载router_helper，路径: ../../../helpers/router_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载router_helper失败，使用备用实现');
  RouterHelper = {
    navigateTo: (url) => wx.navigateTo({ url })
  };
}

// 7. 加载FileHelper
try {
  FileHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载file_helper，路径: ../../../helpers/file_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载file_helper失败，使用备用实现');
  FileHelper = {
    openDoc: () => wx.showToast({ title: '文件功能未实现', icon: 'none' })
  };
}

// 8. 加载CacheHelper
try {
  CacheHelper = require('../config/path_resolver.js').pageHelper;
  console.log('成功加载cache_helper，路径: ../../../helpers/cache_helper.js');
} catch (e) {
  // 使用备用实现
  console.warn('加载cache_helper失败，使用备用实现');
  CacheHelper = { 
    set: (k, v) => wx.setStorageSync(k, v),
    get: (k) => wx.getStorageSync(k),
    remove: (k) => wx.removeStorageSync(k) 
  };
}

// 创建默认的研发状态机实现
const defaultResearchStateBiz = {
  // 模拟状态定义
  PROJECT_STATUS: {
    PENDING: 0,
    REVIEWING: 1,
    DORMANT: 2,
    ACTIVE: 3,
    COMPLETED: 99
  },
  
  // 模拟角色配置
  ROLE_SIMULATION: {
    ENABLED: false,
    ADMIN_ONLY: false,
    ALLOWED_ROLES: [],
    LOG_ACTIONS: true
  },
  
  // 模拟方法
  getStatusName: (status) => {
    const statusNames = {
      0: '待立项',
      1: '项目审核',
      2: '休眠',
      3: '活动',
      99: '完成'
    };
    return statusNames[status] || `状态${status}`;
  },
  
  enableStateDebugMode: () => {
    console.log('[模拟]启用状态调试模式');
    return true;
  },
  
  disableStateDebugMode: () => {
    console.log('[模拟]禁用状态调试模式');
    return true;
  },
  
  setRoleSimulationEnabled: () => true,
  getRoleSimulationConfig: () => ({ enabled: false, canUse: true }),
  hasPermission: () => true,
  hasEventPermission: () => true
};

// 设置默认值并尝试加载研发状态机业务逻辑
researchStateBiz = defaultResearchStateBiz;

try {
  // 尝试直接引用
  const directImpl = require('../comm/biz/research_state_biz_direct.js');
  console.log('成功直接加载研发状态机实现');
  researchStateBiz = directImpl;
} catch (directError) {
  console.warn('直接加载研发状态机实现失败, 使用默认实现:', directError.message);
}

// 导出所有模块
module.exports = {
  TimeHelper,
  CloudHelper,
  DataHelper,
  PageHelper,
  ValidateHelper,
  RouterHelper,
  FileHelper,
  CacheHelper,
  researchStateBiz
}; 